package freespiritsocial.io.user.ui.fragment.mine

import android.os.Bundle
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import com.kingja.loadsir.core.LoadSir
import com.scwang.smart.refresh.layout.util.SmartUtil.dp2px
import freespiritsocial.io.user.R
import freespiritsocial.io.user.base.BaseFragment
import freespiritsocial.io.user.databinding.FrgNotificationsBinding
import freespiritsocial.io.user.decoration.SpaceItemDecoration
import freespiritsocial.io.user.ext.clearData
import freespiritsocial.io.user.ext.init
import freespiritsocial.io.user.ext.loadListData
import freespiritsocial.io.user.ext.setTitle
import freespiritsocial.io.user.handle.BackHandle
import freespiritsocial.io.user.ui.adapter.NotificationsAdapter
import freespiritsocial.io.user.ui.fragment.post.PostDetailFrg
import freespiritsocial.io.user.util.CacheUtil
import freespiritsocial.io.user.viewmodel.NotificationsViewModel
import freespiritsocial.io.user.weight.BottomCancelDialog
import freespiritsocial.io.user.weight.loadCallback.NotificationEmptyCallback
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import kotlin.math.abs

/**
 * @description 通知页
 */
class NotificationsFrg: BaseFragment<NotificationsViewModel,FrgNotificationsBinding>() {
    private val adapterWeek by lazy(LazyThreadSafetyMode.NONE) {
        getAdapter()
    }
    private val adapterMonth by lazy(LazyThreadSafetyMode.NONE) {
        getAdapter()
    }

    private fun getAdapter() = NotificationsAdapter().apply {
        addChildClickViewIds(R.id.iv_avatar,R.id.iv_cover,R.id.tv_follow)
        setOnItemChildClickListener { adapter,view,position ->
            val notificationPojo = data[position]
            when (view.id) {
                R.id.tv_follow -> {
                    val data = notificationPojo.userInfos?.first()
                    mViewModel.attention(data?.userId,data?.isFollowed ?: false)
                }
                R.id.iv_cover -> {
                    mViewModel.getPost(notificationPojo.invitationId?.toLong()) {
                        nav().navigateAction(
                            R.id.postDetailFrg,
                            bundle = bundleOf(PostDetailFrg.KEY_DATA to it)
                        )
                    }
                }
                R.id.iv_avatar -> {
                    mViewModel.getUserInfo(notificationPojo.userInfos?.first()?.userId) {
                        nav().navigateAction(R.id.mineFrg,bundleOf(MineFrg.KEY_IS_USER to false,MineFrg.KEY_USER to it))
                    }
                }
            }
        }
    }


    private val notificationSetting by lazy(LazyThreadSafetyMode.NONE) {
        CacheUtil.getNotificationSetting()
    }

    private val loadService by lazy {
        LoadSir.beginBuilder().addCallback(NotificationEmptyCallback()).build().register(mDatabind.ll)
    }

    override fun layoutId(): Int = R.layout.frg_notifications

    override fun initView(savedInstanceState: Bundle?) = with(mDatabind) {
        click = Click()
        loadService.showSuccess()
        recyclerWeek.init(adapterWeek,hasEmpty = false)
            .addItemDecoration(SpaceItemDecoration(dp2px(20f),dp2px(20f)))
        adapterWeek.setHeaderView(TextView(context).apply {
            textSize = 13f
            text = "This week"
            paint.isFakeBoldText = true
        })
        recyclerMonth.init(adapterMonth,hasEmpty = false)
            .addItemDecoration(SpaceItemDecoration(dp2px(20f),dp2px(20f)))
        adapterMonth.setHeaderView(TextView(context).apply {
            textSize = 13f
            text = "This month"
            paint.isFakeBoldText = true
        })
        root.setTitle(getString(R.string.notifications))
        initNotificationSetting()
    }

    private fun initNotificationSetting() {
        notificationSetting?.apply {
            mDatabind.switchLikes.isChecked = likeOnOff != 0
            mDatabind.switchComments.isChecked = commentsOnOff != 0
            mDatabind.switchStories.isChecked = storiesOnOff != 0
        }
    }

    override fun dismissLoading() {
        mDatabind.refresh.finishLoadMore()
        mDatabind.refresh.finishRefresh()
        super.dismissLoading()
    }

    override fun createObserver() {
        super.createObserver()
        eventViewModel.attentionEvent.observe(this) {
            adapterWeek.data.forEachIndexed { index,data ->
                val user = data.userInfos?.first()
                if (user?.userId == it) {
                    user?.changeFollowStatus()
                    adapterWeek.notifyItemChanged(index + adapterWeek.headerLayoutCount)
                }
            }
            adapterMonth.data.forEachIndexed { index,data ->
                val user = data.userInfos?.first()
                if (user?.userId == it) {
                    user?.changeFollowStatus()
                    adapterMonth.notifyItemChanged(index + adapterMonth.headerLayoutCount)
                }
            }
        }
        mViewModel.weekResult.observe(this) {
            loadListData(it,adapterWeek,mDatabind.refresh)
            mDatabind.recyclerWeek.isVisible = adapterWeek.data.isNotEmpty()
            if (mDatabind.recyclerWeek.isVisible.not() && mDatabind.recyclerMonth.isVisible.not()) {
                loadService.showCallback(NotificationEmptyCallback::class.java)
            }
        }
        mViewModel.monthResult.observe(this) {
            loadListData(it,adapterMonth,mDatabind.refresh)
            mDatabind.recyclerMonth.isVisible = adapterMonth.data.isNotEmpty()
            if (mDatabind.recyclerWeek.isVisible.not() && mDatabind.recyclerMonth.isVisible.not()) {
                loadService.showCallback(NotificationEmptyCallback::class.java)
            }
        }
    }


    override fun lazyLoadData() {
        mViewModel.getPushInfoList()
    }

    inner class Click: BackHandle {
        override fun goBack() {
            nav().navigateUp()
        }

        fun clear() {
            BottomCancelDialog(
                requireContext(),
                title = "Clear Notifications",
                message = "All Notifications will be deleted. Are you sure you want to continue?"
            ) {
                mViewModel.clearAllPush {
                    adapterWeek.clearData()
                    adapterMonth.clearData()
                    loadService.showCallback(NotificationEmptyCallback::class.java)
                }
            }.show(childFragmentManager,"cancel")
        }

        fun likes() {
            val likeOnOff = abs(notificationSetting?.likeOnOff?.minus(1) ?: 0)
            mViewModel.setNotificationSetting(likeOnOff = likeOnOff)
            notificationSetting?.likeOnOff = likeOnOff
            CacheUtil.setNotificationSetting(notificationSetting)
        }

        fun comments() {
            val commentsOnOff = abs(notificationSetting?.commentsOnOff?.minus(1) ?: 0)
            mViewModel.setNotificationSetting(commentsOnOff = commentsOnOff)
            notificationSetting?.commentsOnOff = commentsOnOff
            CacheUtil.setNotificationSetting(notificationSetting)
        }

        fun stories() {
            val storiesOnOff = abs(notificationSetting?.storiesOnOff?.minus(1) ?: 0)
            mViewModel.setNotificationSetting(storiesOnOff = storiesOnOff)
            notificationSetting?.storiesOnOff = storiesOnOff
            CacheUtil.setNotificationSetting(notificationSetting)
        }

        fun refresh() {
            loadService.showSuccess()
            mViewModel.getPushInfoList()
        }

        fun loadMore() {
            mViewModel.getPushInfoList(adapterMonth.data.lastOrNull()?.pushId ?: adapterWeek.data.lastOrNull()?.pushId ?: return)
        }
    }
}